﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace Tzync
{
    public partial class ProfileUIForm : Form
    {
        private String systemId, profileName, rootAddress;
        private SyncTool syncTool;
        private Profile profile;
        private List<String> profileList = new List<String>();  //list of profiles
        private DialogResult dialog;

        public ProfileUIForm()
        {
            systemId = Utility.GetCPUId();  //get CPU id of this computer
            syncTool = new SyncTool(systemId);  //start facade class
            InitializeComponent();            
        }

        private void ProfileUIForm_Load(object sender, EventArgs e)
        {
            DisplayProfile();

            //tooltips  
            logoToolTip.SetToolTip(tzyncLogoPB, "Click here to visit Tzync's website!");
            newBtnToolTip.SetToolTip(createProfileBtn, "Click here to create a new profile");
            loadBtnToolTip.SetToolTip(loadProfileBtn, "Click here to load the selected profile");
            deleteBtnToolTip.SetToolTip(deleteProfileBtn, "Click here to remove the selected profile");
            helpBtnToolTip.SetToolTip(helpBtn, "Click here to get online help for Tzync!");
            quitBtnToolTip.SetToolTip(quitBtn, "Why leave when you are having fun?");
        }

        private void ProfileUIForm_Shown(object sender, EventArgs e)
        {
            DisplayProfile();
            infoLabel.Text = "";
        }

        private void tzyncLogoPB_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            Process.Start("http://code.google.com/p/tzync/");
        }

        private void CreateProfileBtn_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            this.Visible = false;
            AddNewProfileUIForm newProfileUI = new AddNewProfileUIForm(syncTool);
            newProfileUI.ShowDialog();
            this.Visible = true;
            DisplayProfile();
        }

        private void loadProfileBtn_Click(object sender, EventArgs e)
        {
            MatchProfileUIForm matchProfileUI;
            RenameProfileUIForm renameProfileUI;
            SyncUIForm syncUI;
            bool directoryExists;
            bool matched = false;

            infoLabel.Text = "";
            ListView.SelectedListViewItemCollection selectedProfile = profileLV.SelectedItems;

            if (selectedProfile.Count > 0)
            {
                foreach (ListViewItem item in selectedProfile)
                    profileName = item.Text;

                try
                {
                    syncTool.LoadProfile(profileName);  //retrieve profile Information 
                }
                catch (FileNotFoundException f)
                {
                    infoLabel.Text = "Rollback folder at '" + f.FilePath + "' not found!";
                    return;
                }

                profile = syncTool.GetProfile();

                if (profile.SystemName == SystemType.Host)
                    rootAddress = profile.RootAddressA;
                else
                    rootAddress = profile.RootAddressB;

                if (!profile.HasB && systemId != profile.CPUIdA)   //if profile needs to be completed
                {
                    this.Visible = false;
                    matchProfileUI = new MatchProfileUIForm(syncTool, ref matched);
                    matchProfileUI.ShowDialog();
                    this.Visible = true;
                    infoLabel.Text = "";
                    profile = syncTool.GetProfile();
                    DisplayProfile();
                }
                else 
                    matched = true;
                
                directoryExists = CheckProfileFolder();

                if (profile.HasB && !directoryExists)   //profile folder has been renamed, deleted, or moved
                {
                    this.Visible = false;
                    renameProfileUI = new RenameProfileUIForm(syncTool, ref matched);
                    renameProfileUI.ShowDialog();
                    this.Visible = true;
                    infoLabel.Text = "";
                    profile = syncTool.GetProfile();
                    DisplayProfile();

                    //If the user deleted the folder, no need to display main screen
                    directoryExists = CheckProfileFolder();
                    if (directoryExists == false)
                    {
                        infoLabel.Text = "Profile has been deleted!";
                        DisplayProfile();
                        return;
                    }
                }

                if (matched)    //show main screen if profile is ok 
                {
                    this.Visible = false;
                    syncUI = new SyncUIForm(syncTool);
                    dialog = syncUI.ShowDialog();

                    if (dialog == DialogResult.OK)
                    {
                        this.Visible = true;
                        infoLabel.Text = "";
                        DisplayProfile();
                    }
                }
                else
                    return;
            }
            else
            {
                infoLabel.Text = "No profile was selected to load!";
                return;
            }
        }

        private void profileLV_DoubleClick(object sender, EventArgs e)
        {
            foreach (ListViewItem item in profileLV.SelectedItems)
                loadProfileBtn_Click(sender, e);
        }

        //checks if profile folder is missing
        private bool CheckProfileFolder()
        {
            if (profile.SystemName == SystemType.Host)
            {                
                if (!Directory.Exists(profile.RootAddressA))
                    return false;
                else
                    return true;
            }
            else
            {
                if (!Directory.Exists(profile.RootAddressB))
                    return false;
                else
                    return true;
            }
        }

        private void deleteProfileBtn_Click(object sender, EventArgs e)
        {
            ListView.SelectedListViewItemCollection selectedProfile = profileLV.SelectedItems;
            if (selectedProfile.Count > 0)
            {
                DialogResult deleteDialog = MessageBox.Show("Are you sure you want to delete the selected profile?",
                "Important!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (deleteDialog == DialogResult.Yes)
                {
                    infoLabel.Text = "Deleting in progress...";
                    Cursor.Current = Cursors.WaitCursor;
                    foreach (ListViewItem item in selectedProfile)
                    {
                        syncTool.RemoveProfile(item.Text);  //remove profile
                        profileLV.Items.Remove(item);
                    }

                    infoLabel.Text = "Selected profile(s) have been removed!";
                    Cursor.Current = Cursors.Default;
                }
                else
                    return;
            }
            else
            {
                infoLabel.Text = "No profile was selected for removal!";
                return;
            }
        }

        private void quitBtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void helpBtn_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            Process.Start("http://tzync.googlecode.com/files/Tzync_User_Guide_V1.pdf");
        }

        //displays list of profiles
        private void DisplayProfile()
        {
            infoLabel.Text = "";
            profileLV.Items.Clear();
            Profile newProfile;
            profileList = syncTool.GetAvailableProfiles();
            foreach (String profileName in profileList)
            {
                newProfile = new Profile(systemId, profileName);
                ListViewItem profileLVI = new ListViewItem();
                profileLVI.Text = newProfile.ProfileName;
                profileLVI.SubItems.Add(newProfile.RootAddressA);
                profileLVI.SubItems.Add(newProfile.RootAddressB);
                profileLV.Items.Add(profileLVI);

                ResizeColumns();
            }
        }

        //auto resize columns
        private void ResizeColumns()
        {
            int contentWidth, headerWidth;
            ColumnHeaderAutoResizeStyle headerResize;

            for (int index = 0; index < profileLV.Columns.Count; index++)
            {
                ColumnHeader header = profileLV.Columns[index];
                header.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                contentWidth = header.Width;

                header.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                headerWidth = header.Width;

                if (contentWidth > headerWidth)
                    headerResize = ColumnHeaderAutoResizeStyle.ColumnContent;
                else
                    headerResize = ColumnHeaderAutoResizeStyle.HeaderSize;

                header.AutoResize(headerResize);
            }
        }
    }
}
